// app.js
App({

  //通用网络请求封装
  requestUtil: function (url, method,headers,data,succ,fail){
    headers = headers || { "Content-Type": "application/json;charset=UTF-8"};
    wx.request({
      url: url,  
      method:method,
      data: data,
      header: headers,
      success(res) {
        succ(res);
      },
      fail(err){
        fail(err);
      }
    })
  },

  //带认证的请求头请求
  requestWithAuth:function(url,method,headers,data,succ){
    headers = headers || {};
    let login_info_key = wx.getStorageSync(getApp().globalData.login_info_key);
    const self = this;
    //调用原请求接口
    headers['token'] = login_info_key.token;
    self.requestUtil(url, method, headers, data, res => {
      if (res.statusCode != 200) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '系统异常' + res.statusCode,
        })
      } else {
        if (res.data.code == 0) {
            succ(res);
            wx.hideLoading()
        }else if(res.data.code == -1){
          wx.hideLoading()
          wx.removeStorageSync(this.globalData.login_info_key)
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg || '错误码:' + res.data.code
          })
        }else if(res.data.code == 401){
          return new Promise(function(resolve, reject) {
            self._login(() => {
              //调用原请求接口
              self.requestWithAuth(url, method, headers, data, res => {
                resolve(res.data);
              });
            }, () => {},true);
          })
        }else{
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg || '错误码:' + res.data.code
          })
        }
      }
    }, err => {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: JSON.stringify(err),
      })
    })

  },

  //网络请求封装
  getData: function(url, method, data, headers = {
    "Content-Type": "application/json;charset=UTF-8"
  },) {
    let login_info_key = wx.getStorageSync(getApp().globalData.login_info_key).token;
    const self = this;
    return new Promise(function(resolve, reject) {
      wx.showLoading({
        title: '加载中',
      });
      if (!login_info_key) {
          //再次调用登录
          self._login(() => {
            //调用原请求接口
            self.requestWithAuth(self.globalData.siteUrl + url, method, headers, data, res => {
              resolve(res.data);
            });
          }, () => {},true);
      } else {//非刷新时调用
        //调用原请求接口
        self.requestWithAuth(self.globalData.siteUrl + url, method, headers, data, res => {
          resolve(res.data);
        });
      }
    });
  },
  //登录
  _login:function(succ,fi,force=false){
    var _self = this;
    wx.login({
      success:res =>{
        if(res.code){
          var data ={
            code:res.code
          }
          wx.request({
            url: this.globalData.siteUrl + 'login',
            data: data,
            method: 'POST',
            header: {
              "Content-Type": "application/json;charset=UTF-8",
            },
            success: function (res) {
              if (res.statusCode != 200) {
                wx.hideLoading();
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: '系统异常' + res.statusCode
                })
                fi();
              } else {
                if (res.data.code == 0) {
                  wx.hideLoading();
                  // resolve(res.data);
                  var tokenObj = {};
                  //token 失效时间
                  // tokenObj.expire = new Date().getTime() + res.data.expire * 1000;
                  tokenObj.token = res.data.token;
                  wx.setStorageSync(_self.globalData.login_info_key, tokenObj); 
                  succ();
                } else {
                  wx.hideLoading();
                  wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: res.data.msg || '错误码:' + res.data.code
                  })
                  fi();
                }
    
              }
            },
            fail: function (err) {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: JSON.stringify(err),
              })
              fi();
            }
          })
        }
      }
    })
  },
  //页面跳转传参
  navigateToUrl: function (url, params = {}) {
    wx.navigateTo({
      url: url + '?params=' + encodeURIComponent(JSON.stringify(params)),
    })
  },
  //解析页面传递过来的参数
  parsePageParams: function (options) {
    return JSON.parse(decodeURIComponent(options.params))
  },

  onLaunch() {
    // 展示本地存储能力
    var _self = this;
    // this.calcNavBarInfo()
    // const logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    wx.getSystemInfo({
      success: res => {
        this.globalData.system = res
      }
    })

    this.globalData.capsule = wx.getMenuButtonBoundingClientRect()
  },

  globalData: {
    userInfo: null,
    siteUrl: 'https://ar.glkj.online/yun-museum-ar/app/miniapp/',//生产环境
    login_info_key: 'login_info_key',
    system: '',
    capsule: ''
  }
})
